from typing import List, Dict, Optional

from pydantic import BaseModel, validator

DB_ACCESS_LOG = "access_log"
DB_ACCESS_LOG_CONFIG = "access_log_config"


class PaginationNode(BaseModel):
    page: Optional[int] = 1  # 查询页
    size: Optional[int] = 50  # 页返回条数

    @validator(*["page", "size"], pre=True, always=True)
    def check_page(cls, v):
        if v <= 0:
            raise ValueError("分页参数, 必须大于0, 当前:{}".format(v))
        return int(v)

    def get_limit(self):
        return int(self.size)

    def get_skip(self):
        return int(self.page - 1) * self.get_limit()


class TableSelect:
    """下拉选择"""
    # bool类型选择
    API_RESPONSE_CODE: List[Dict] = [
        {
            "label": "成功",
            "prop": "success"
        },
        {
            "label": "失败",
            "prop": "fail"
        },
    ]


class HeaderCollection:
    """查询header"""
    # 异常类型配置
    SERVER_LOG_HEAD: List[Dict] = [
        {
            "label": "工序编码",
            "prop": "process_code"
        },
        {
            "label": "工序名称",
            "prop": "process_name"
        },
        {
            "label": "设备编码",
            "prop": "device_code"
        },
        {
            "label": "设备名称",
            "prop": "device_name"
        },
        {
            "label": "调用接口",
            "prop": "url_name"
        },
        {
            "label": "调用时间",
            "prop": "time"
        },
        {
            "label": "耗时",
            "prop": "cost_time"
        },
        {
            "label": "返回结果",
            "prop": "code"
        },
        {
            "label": "用户编码",
            "prop": "user_code"
        },
        {
            "label": "用户名",
            "prop": "user_name"
        },
    ]

    SERVER_LOG_CONFIG_HEAD = [
        {
            "label": "接口名称",
            "prop": "url_name"
        },
        {
            "label": "接口url",
            "prop": "url"
        },
    ]


GROUP_DEVICE_STRUCTURE = [
    {
        "$group": {
            "_id": {
                "produce_unit_code": "$生产单元代号",
            },
            "device_info": {
                "$push": {
                    "device_name": "$设备名称",
                    "device_code": "$设备编码"
                }
            }
        }
    },
    {
        '$project':
            {
                'produce_unit_code': '$_id.produce_unit_code',
                'device_info': 1,
                '_id': 0
            }
    },
]
